<template>
    <div>
        <u-popup :show="show" :round="16" mode="bottom" @close="close">
            <div class="vest-mian">
                <ul class="vest-tab" v-if="!vestFlag">
                    <li :class="{ active: activeTab === 'vest' }" @tap="activeTab = 'vest'">固定马甲</li>
                    <li :class="{ active: activeTab === 'speech' }" @tap="speechVest = null; activeTab = 'speech'">快速发言
                    </li>
                </ul>

                <div class="tab-vest-content" v-if="activeTab === 'vest'">
                    <template v-if="!vestFlag">
                        <div class="vest-tip">
                            <p> 1、开启固定马甲后，您将以当前选中的马甲发言 </p>
                            <p> 2、开启后，可在主界面点击左下角的头像框</p>
                        </div>
                        <div class="vest-switch">
                            <div>开启固定马甲</div>
                            <u-switch size="22" @change="handleChange" v-model="isFixedVest"></u-switch>
                        </div>
                    </template>
                    <div v-else class="flex-center-between" style="padding: 0 16px 16px;">
                        <div>当前固定马甲</div> <i class="close-icon" @click="show = false"></i>
                    </div>

                    <div class="vest-item" v-if="fixedVest">
                        <div class="vest-item-info">
                            <div class="info-avatar">
                                <img :src="fixedVest.avatar" alt="">
                            </div> {{ fixedVest.nickname }}
                        </div>
                        <div class="vest-item-action">
                            <span @click="editVest(fixedVest)">编辑</span>
                            <span @click="getRandVest">换一个</span>
                            <span v-if="!vestFlag" @click="handleSpeech(fixedVest)">快速发言</span>
                        </div>

                    </div>
                    <div class="vest-store">
                        <div class="vest-store-mine">我的马甲库 <span>({{ vestList.length }}/100)</span></div>
                        <div class="vest-store-action">
                            <span @click="createVest">新增马甲</span>
                            <span @click="currentType = 2; activeTab = 'speech'">库内快速发言</span>
                        </div>
                    </div>
                    <scroll-view refresher-enabled="true" :refresher-triggered="triggered" @refresherrefresh="onRefresh"
                        @scrolltolower="scrolltolower" scroll-y scroll-with-animation class="vest-item-list">
                        <div :class="['vest-item', item.isDefault && fixedVest.vestUseId ? 'active' : '']"
                            :key="item.vestUseId" @click="switchVest(item.vestUseId)" v-for="item in vestList">
                            <div class="vest-item-info">
                                <div class="info-avatar">
                                    <img :src="item.avatar" alt="">
                                    <i class="selected-icon"></i>
                                </div> {{ item.nickname }}
                            </div>
                            <div class="vest-item-action">
                                <span @click.stop="editVest(item)">编辑</span>
                                <span @click.stop="currentVestUseId = item.vestUseId; delVestModal = true">删除</span>
                                <span v-if="!vestFlag" @click.stop="handleSpeech(item)">快速发言</span>
                            </div>
                        </div>
                        <u-empty text="暂无数据" v-if="!vestList.length" icon="https://vlive-static.vlebo.cn/empty.png" />
                    </scroll-view>
                </div>
                <div class="tab-speech-content" v-else>
                    <div class="speech-store">
                        <div class="flex-center-between speech-store-item">
                            <div> 马甲 </div>
                            <div v-if="speechVest">
                                <img :src="speechVest.avatar" alt="" srcset="">
                            </div>
                            <div v-else @click="vestStoreModal = true" class="flex-center"> {{ currentTypeName }} <i
                                    class="down-icon"></i></div>
                        </div>
                        <div class="flex-center-between speech-store-item">
                            <div> 评论库 </div>
                            <div @click="commentStroeModal = true" class="flex-center">{{ commentStroeList.find(item =>
            item.packageId === currentPackageId)['name'] }}
                                <i class="down-icon"></i>
                            </div>
                        </div>
                    </div>
                    <div scroll-with-animation class="speech-comment-list">
                        <div class="flex-center-between speech-comment-item" v-for="item in commentList">
                            <span>{{ item.content }}</span>
                            <span @click="send(item.content)">发送</span>
                        </div>
                        <u-empty text="暂无数据" v-if="!vestList.length" icon="https://vlive-static.vlebo.cn/empty.png" />
                    </div>
                    <div class="speech-comment-action" @tap="commentModal = true">
                        添加评论
                    </div>
                </div>
                <u-action-sheet :round="12" :actions="typelist" @select="selectClick" :show="vestStoreModal"
                    @close="vestStoreModal = false" cancelText="取消"></u-action-sheet>
                <u-popup :round="8" :show="commentModal" mode="center" :closeOnClickOverlay='false'>
                    <div class="comment-modal-main">
                        <div class="comment-modal-title flex-center">添加评论

                            <i class="close-icon" @tap="commentModal = false"></i>
                        </div>
                        <u--textarea :height='127' class="comment-modal-content" maxlength="200" v-model="content"
                            placeholder="请输入" count></u--textarea>
                        <div class="comment-modal-action" @tap="createComment">
                            确定添加
                        </div>
                    </div>
                </u-popup>
                <u-popup :round="8" :show="editVestModal" v-if="editVestData" mode="center"
                    :closeOnClickOverlay='false'>
                    <div class="edit-vest">
                        <div class="edit-vest-title">编辑马甲</div>
                        <div class="edit-vest-info">
                            <div>头像：</div>
                            <div @click="choosePic" class="flex-center"><img :src="editVestData.avatar" alt=""> <i
                                    class="right-icon"></i>
                            </div>
                        </div>
                        <div class="edit-vest-info">
                            <div>昵称：</div>
                            <div class="flex-center"> <u--input inputAlign="right" v-model="editVestData.nickname"
                                    border="none"></u--input><i class="right-icon"></i></div>
                        </div>
                        <div class="edit-vest-action">
                            <span @tap='editVestModal = false'>取消</span>
                            <span @tap="handleEdit">确定</span>
                        </div>
                    </div>
                </u-popup>
                <u-modal width="320px" @confirm="confirm" @cancel="cancel" showCancelButton :show="delVestModal"
                    content='确定删除该马甲吗？'></u-modal>
            </div>
        </u-popup>



        <u-popup :round="8" :show="commentStroeModal" mode="bottom" :closeOnClickOverlay='false'>
            <div class="comment-stroe-modal-main">
                <div class="comment-stroe-modal-title">评论库
                    <i class="left-icon" @tap="commentStroeModal = false"></i>
                    <i class="close-icon" @tap="commentStroeModal = false"></i>
                </div>
                <div class="comment-stroe-modal-list">
                    <div class="comment-stroe-modal-item" @click="handleSelect(item.packageId)"
                        v-for="item in  commentStroeList" :key='item.packageId'>
                        <i :class="[currentPackageId === item.packageId ? 'check-icon' : 'icon']"></i> {{ item.name }}
                    </div>
                </div>
                <div class="comment-stroe-modal-action" @tap="commentStroeModal = false">
                    确定
                </div>
            </div>
        </u-popup>


    </div>
</template>

<script>
import {
    txCosUpload
} from '@/utils/txCosUpload'
import { mapState } from 'vuex';
import liveInfo from '@/mixins/liveInfo';
import { getVestList, createVest, deleteVest, editVest, switchVest, getRandVest } from '@/api/vest'
import { getCommentList, createComment, getPackageList } from '@/api/comment'
import EventBus from '@/utils/eventBus'
export default {
    mixins: [liveInfo],
    data() {
        return {
            vestFlag: false,
            commentList: [],
            currentVestUseId: '',
            currentPackageId: '',
            triggered: true,
            commentStroeModal: false,
            commentStroeList: [],
            commentModal: false,
            vestStoreModal: false,
            editVestModal: false,
            delVestModal: false,
            show: false,
            isFixedVest: false,
            editVestData: null,
            fixedVest: null,
            speechVest: null,
            content: '',
            activeTab: 'vest',
            vestList: [],
            currentType: 3,
            typelist: [
                {
                    name: '当前固定马甲',
                    id: 1

                },
                {
                    name: '我的马甲库',
                    id: 2

                },
                {
                    name: '系统马甲',
                    id: 3
                },

            ],
        }
    },
    computed: {
        ...mapState({
            user(state) {
                return state.user;
            },
        }),
        currentTypeName() {
            let data = this.typelist.find(item => item.id === this.currentType)
            return data.name
        }
    },
    mounted() {
        EventBus.$on(EventBus.vest, () => {
            this.activeTab = 'vest'
            this.vestFlag = true
            this.show = true
        })
        this.isFixedVest = uni.getStorageSync("isFixedVest") || false
        this.fixedVest = uni.getStorageSync("fixedVest") || null
        if (!this.fixedVest) {
            this.getRandVest()
        }
        this.getVestList()
        this.getPackageList()
    },
    methods: {
        choosePic() {
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: async (res) => {
                    const file = res.tempFiles[0];
                    const params = {
                        scene: 'business_avatar'
                    }
                    txCosUpload(file, params, (progressData) => {
                        // 实现进度条，目前没用到
                    },).then(fileRes => {
                        uni.showToast({
                            title: '上传成功',
                            icon: 'none',
                            duration: 1500
                        })
                        this.editVestData.avatar = fileRes.fileUrl

                    })
                },
                fail: (res) => {
                    console.log('上传图片fail', res)
                }
            });
        },

        async send(content) {
            let avatar = ''
            let nickname = ''
            if (this.speechVest) {
                avatar = this.speechVest.avatar
                nickname = this.speechVest.nickname
            } else {
                switch (this.currentType) {
                    case 1:
                        avatar = this.fixedVest.avatar
                        nickname = this.fixedVest.nickname
                        break;
                    case 2:
                        const randomIndex = Math.floor(Math.random() * this.vestList.length);
                        avatar = this.vestList[randomIndex].avatar
                        nickname = this.vestList[randomIndex].nickname
                        break;

                    case 3:
                        const data = await getRandVest()
                        avatar = data.avatar
                        nickname = data.nickname
                        break;
                    default:
                        break;
                }

            }
            this.$tim.updateUserInfo({ avatar, username: nickname });

            const res = await this.$tim
                .sendMessage(this.mix_liveId, {
                    content,
                    v: this.currentType === 3 ? 2 : 1
                })
            uni.showToast({
                title: '发送成功',
                icon: 'none',
            })
            this.$root.$refs.commentRef.commentActionSend(res)
        },
        async createComment() {
            await createComment({
                "packageId": this.currentPackageId,
                "content": this.content
            })

            this.getCommentList()
            this.content = ''
            this.commentModal = false
        },
        async getCommentList() {
            const { list } = await getCommentList({
                "packageId": this.currentPackageId,
            })
            this.commentList = list
            console.log(this.commentList)

        },
        handleSelect(id) {
            this.currentPackageId = id
            uni.setStorageSync("currentPackageId", id)
            this.getCommentList()
        },
        async getPackageList() {
            const { list } = await getPackageList()
            this.commentStroeList = list || []
            let defaultId = list[0]?.packageId ?? ''
            this.currentPackageId = uni.getStorageSync("currentPackageId") || defaultId
            this.getCommentList()
        },
        handleSpeech(item) {
            this.speechVest = item
            this.currentType = 2
            this.activeTab = 'speech'
        },
        async getRandVest() {
            const data = await getRandVest()
            this.fixedVest = data
            uni.setStorageSync("fixedVest", this.fixedVest)
            if (this.isFixedVest && data) {
                this.$store.commit('user/SET_NICKNAMEIM', data.nickname);
                this.$store.commit('user/SET_AVATARIM', data.avatar);
            }

        },
        async deleteVest(vestUseId) {
            await deleteVest({ vestUseId })
            this.delVestModal = false
            this.getVestList()

        },
        async handleEdit() {
            if (!this.editVestData.nickname) {
                return uni.showToast({
                    title: '昵称不能为空',
                    icon: 'none',
                })
            }
            if (this.editVestData.vestUseId) {
                await editVest(
                    { ...this.editVestData }
                )
                this.getVestList()
            } else {
                this.fixedVest = this.editVestData
                uni.setStorageSync("fixedVest", this.fixedVest)
                if (this.isFixedVest && this.fixedVest) {
                    this.$store.commit('user/SET_NICKNAMEIM', this.fixedVest.nickname);
                    this.$store.commit('user/SET_AVATARIM', this.fixedVest.avatar);
                }
            }

            this.editVestModal = false


        },
        editVest(item) {
            this.editVestData = JSON.parse(JSON.stringify(item))
            this.editVestModal = true
        },
        async switchVest(vestUseId) {
            await switchVest({ vestUseId })
            uni.removeStorageSync("fixedVest")
            this.getVestList()

        },
        async createVest() {
            await createVest()
            this.getVestList()
        },
        async getVestList() {
            const { list } = await getVestList({})
            this.vestList = list;
            this.triggered = false;
            if (!uni.getStorageSync("fixedVest")) {
                let data = this.vestList.find(item => item.isDefault) || null
                if (data) {
                    this.fixedVest = data
                    uni.setStorageSync("fixedVest", data)
                    this.$store.commit('user/SET_NICKNAMEIM', data.nickname);
                    this.$store.commit('user/SET_AVATARIM', data.avatar);
                }
                // else {
                //     if (this.vestLis.length) {
                //         this.fixedVest = this.vestLis[0]
                //         uni.setStorageSync("fixedVest", this.vestLis[0])
                //         return
                //     } else {
                //         this.getRandVest()
                //     }


                // }
            }


        },
        handleChange(val) {
            console.log(val)
            uni.setStorageSync("isFixedVest", val)
            if (val && this.fixedVest) {
                this.$store.commit('user/SET_NICKNAMEIM', this.fixedVest.nickname);
                this.$store.commit('user/SET_AVATARIM', this.fixedVest.avatar);
            }
            if (!val) {
                this.$store.commit('user/SET_NICKNAMEIM', this.user.nickname);
                this.$store.commit('user/SET_AVATARIM', this.user.avatar);
            }
        },
        onRefresh() {
            this.triggered = true;
            this.getVestList()
        },
        // 滚动到底部加载更多
        scrolltolower(e) {
            // uni.showToast({
            //     title: '已到底',
            //     icon: 'none',
            // })
        },

        close() {
            this.show = false
        },

        selectClick(item) {
            this.currentType = item.id
        },
        confirm() { this.deleteVest(this.currentVestUseId); },
        handleDel() {
            this.editVestModal = false;
        },
        cancel() {
            this.delVestModal = false

        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .u-modal__content__text {
    text-align: center;
}

::v-deep .u-textarea__count {
    background: transparent !important;
    bottom: 8px;
}


.flex-center-between {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.flex-center {
    display: flex;
    align-items: center;
    justify-content: center;
}

.vest-item-list {
    height: 200px;
}

.u-empty {
    margin-top: 50px !important;
}

.vest-mian {

    height: 464px;
    position: relative;

    .vest-tab {
        display: flex;
        justify-content: center;
        padding: 16px 0 6px;
        border-bottom: 1px solid #AEC0FE;


        li {
            font-size: 14px;
            color: #8F969E;
            line-height: 22px;

            &:last-of-type {
                margin-left: 100px;
            }

            &.active {
                position: relative;
                font-weight: 500;
                font-size: 16px;
                color: #295EFF;

                &::before {
                    position: absolute;
                    left: 9px;
                    bottom: -6px;
                    content: '';
                    width: 44px;
                    height: 2px;
                    background: #295EFF;
                    border-radius: 1px;
                }

            }
        }
    }

    .tab-vest-content {
        padding: 16px 0;

        .vest-tip {
            height: 54px;
            background: #F6F9FF;
            border-radius: 4px;
            padding: 8px;
            font-size: 12px;
            color: #657180;
            line-height: 17px;
            margin: 0 16px 16px;

            p {
                &:first-of-type {
                    margin-bottom: 4px;
                }
            }
        }

        .vest-switch {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
            color: #464C5B;
            line-height: 20px;
            margin: 0 16px 18px;

        }

        .vest-item {
            padding: 0 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 38px;

            &.active {
                background: rgba(223, 234, 255, 0.2);

                .info-avatar {
                    border: 2px solid #00C795;

                    i {
                        opacity: 1 !important;
                    }
                }
            }

            .vest-item-info {
                display: flex;
                align-items: center;

                .info-avatar {
                    width: 30px;
                    height: 30px;
                    border-radius: 30px;
                    margin-right: 8px;
                    position: relative;

                    i {
                        position: absolute;
                        right: 0;
                        bottom: 0;
                        opacity: 0;
                    }

                }

                img {
                    width: 100%;
                    height: 100%;
                    border-radius: 30px;
                }

                font-size: 14px;
                color: #464C5B;
                line-height: 20px;
            }

            .vest-item-action {
                display: flex;

                span {
                    height: 24px;
                    background: #FFFFFF;
                    border-radius: 4px;
                    border: 1px solid #C8C9CC;
                    margin-left: 8px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #464C5B;
                    line-height: 24px;
                    text-align: center;
                    width: 56px;

                    &:first-of-type {
                        width: 42px;
                    }

                    &:last-of-type {
                        width: 68px;
                        background: #295EFF;
                        border-radius: 4px;
                        color: #fff;
                        border: none;
                    }
                }
            }




        }

        .vest-store {
            margin: 14px 0 8px;
            padding: 0 16px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            .vest-store-action {
                display: flex;
                align-items: center;
                font-size: 12px;
                color: #295EFF;
                line-height: 17px;

                span {
                    margin-left: 20px;
                }
            }

            .vest-store-mine {
                font-weight: 400;
                font-size: 14px;
                color: #464C5B;
                line-height: 20px;

                span {
                    color: rgba(254, 102, 55, 1);
                }
            }


        }
    }


    .tab-speech-content {
        padding: 16px 16px 60px;

        .speech-store {
            font-size: 14px;
            color: #464C5B;
            line-height: 20px;
            height: 72px;
            background: #F6F9FF;
            border-radius: 4px;
            padding: 10px;
            font-size: 14px;
            color: #464C5B;
            line-height: 20px;

            .speech-store-item {
                margin-bottom: 9px;

                img {
                    height: 22px;
                    width: 22px;
                    border-radius: 22px;
                }
            }
        }

        .speech-comment-list {
            height: 260px;
            overflow-y: auto;


            .speech-comment-item {
                margin-top: 16px;
                font-weight: 400;
                font-size: 14px;
                color: #464C5B;
                line-height: 20px;

                span {
                    &:last-of-type {
                        width: 42px;
                        height: 24px;
                        background: #295EFF;
                        border-radius: 4px;
                        font-size: 14px;
                        color: #FFFFFF;
                        text-align: center;
                        line-height: 24px;
                    }
                }
            }
        }

        .speech-comment-action {
            width: 276px;
            height: 40px;
            background: #295FFF;
            border-radius: 23px;
            font-size: 16px;
            color: #FFFFFF;
            line-height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;

            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
        }
    }

}

.edit-vest {
    padding: 14px 16px 18px;
    width: 326px;


    .edit-vest-title {
        font-weight: 600;
        font-size: 18px;
        color: #1D2129;
        line-height: 25px;
        text-align: center;
        margin-bottom: 24px;
    }

    .edit-vest-info {
        height: 30px;
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        color: #1D2129;
        line-height: 20px;

        img {
            width: 30px;
            height: 30px;
            border-radius: 30px;
        }
    }

    .edit-vest-action {
        margin-top: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        span {
            width: 138px;
            height: 38px;
            background: #FFFFFF;
            border-radius: 23px;
            border: 1px solid #295EFF;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: #295EFF;
            line-height: 24px;

            &:last-of-type {
                background: #295FFF;
                color: #fff;
            }

        }
    }
}



.comment-modal-main {
    width: 326px;
    padding: 14px 16px 18px;



    .comment-modal-title {
        font-weight: 600;
        font-size: 18px;
        color: #1D2129;
        line-height: 25px;
        text-align: center;
        margin-bottom: 8px;
        position: relative;

        .close-icon {
            position: absolute;
            right: 0;
        }
    }

    .comment-modal-content {
        background: #F4F6F7;
        border-radius: 8px;
    }

    .comment-modal-action {
        width: 138px;
        height: 38px;
        background: #295FFF;
        border-radius: 23px;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 16px auto 0;
    }


}

.comment-stroe-modal-main {
    position: relative;
    padding-bottom: 84px;
    height: 464px;

    .comment-stroe-modal-title {
        height: 54px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 16px;
        color: #464C5B;
        border-bottom: 1px solid #D8D8D8;
        position: relative;

        .left-icon {
            position: absolute;
            left: 16px;
        }

        .close-icon {
            position: absolute;
            right: 16px;
        }
    }

    .comment-stroe-modal-action {
        width: 276px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #295FFF;
        border-radius: 23px;
        font-weight: 400;
        font-size: 16px;
        color: #FFFFFF;
        position: absolute;
        bottom: 24px;
        left: 50%;
        transform: translateX(-50%);

    }

    .comment-stroe-modal-list {
        padding: 14px 24px;

        .comment-stroe-modal-item {
            font-weight: 400;
            font-size: 14px;
            color: #464C5B;
            display: flex;
            align-items: center;
            margin-bottom: 18px;

            i {
                margin-right: 10px;

                &.icon {
                    width: 16px;
                    height: 16px;
                    background: #FFFFFF;
                    border-radius: 2px;
                    border: 1px solid #D7DDE4;
                }
            }
        }


    }
}
</style>